using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AssetStudio.GUI
{
    public partial class Plugins
    {
        public class PluginInfo
        {
            public string Name { get; set; }
            public string DisplayName { get; set; }
            public string DownloadUrl { get; set; }
            public string FileName { get; set; }
            public bool IsDownloaded { get; set; } = false;
            public bool IsExternalTool { get; set; }
            public bool IsBuiltInDll { get; set; }
            public bool IsZipFile { get; set; }
            public string ExeFileName { get; set; }
            public string ExtractFolder { get; set; }
            public string PluginType
            {
                get
                {
                    if (IsBuiltInDll) return "类库文件";
                    if (IsExternalTool) return "可执行程序";
                    if (IsZipFile) return "压缩包文件";
                    return "PE文件";
                }
            }
        }

        public static List<PluginInfo> plugins = new List<PluginInfo>
        {
            new PluginInfo
            {
                Name = "UniversalFileExtractor",
                DisplayName = "万能二进制提取器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/FileExtractor.dll",
                FileName = "FileExtractor.dll",
                IsExternalTool = false,
                IsBuiltInDll = true
            },
            new PluginInfo
            {
                Name = "UniversalByteRemover",
                DisplayName = "万能字节移除器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/ByteRemover.dll",
                FileName = "ByteRemover.dll",
                IsExternalTool = false,
                IsBuiltInDll = true
            },
            new PluginInfo
            {
                Name = "FavoritesManager",
                DisplayName = "收藏夹管理器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/FavoritesManager.dll",
                FileName = "FavoritesManager.dll",
                IsExternalTool = false,
                IsBuiltInDll = true
            },
            new PluginInfo
            {
                Name = "quickbmsbatch",
                DisplayName = "quickbms批量提取器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/quickbmsbatch.dll",
                FileName = "quickbmsbatch.dll",
                IsExternalTool = false,
                IsBuiltInDll = true
            },
            new PluginInfo
            {
                Name = "SuperToolbox",
                DisplayName = "超级工具箱",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Super-toolbox.dll",
                FileName = "Super-toolbox.dll",
                IsExternalTool = false,
                IsBuiltInDll = true
            },          
            new PluginInfo
            {
                Name = "Sofdec2Viewer",
                DisplayName = "USM视频查看器汉化版",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Sofdec2_Viewer.exe",
                FileName = "Sofdec2_Viewer.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "RadVideo",
                DisplayName = "bink视频播放器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/radvideo64.exe",
                FileName = "radvideo64.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "QuickBMS",
                DisplayName = "quickbms汉化版",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/quickbms.exe",
                FileName = "quickbms.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "quickbms_4gb_files",
                DisplayName = "quickbms_4gb_files汉化版",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/quickbms_4gb_files.exe",
                FileName = "quickbms_4gb_files.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "RioX",
                DisplayName = "RioX汉化版",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/RioX.exe",
                FileName = "RioX汉化版.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "PakExplorer",
                DisplayName = "LUCA system pak解包器汉化版",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/pak_explorer.exe",
                FileName = "pak_explorer.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "PSound",
                DisplayName = "PlayStation音频提取器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/PSound.exe",
                FileName = "PSound.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "WinAsar",
                DisplayName = "WinAsar汉化版",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/WinAsar.exe",
                FileName = "WinAsar汉化版.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "WinAsar",
                DisplayName = "AudioCUE编辑器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/ACE.exe",
                FileName = "ACE.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "WinPCK",
                DisplayName = "完美世界pck解包工具",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/WinPCK.exe",
                FileName = "WinPCK.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "RetsukoSoundTool",
                DisplayName = "3ds/wiiu音频提取器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/RetsukoSoundTool.exe",
                FileName = "RetsukoSoundTool.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "Motrix",
                DisplayName = "免费不限速下载器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Motrix_x64.exe",
                FileName = "Motrix_x64.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "UmodelHelper",
                DisplayName = "Umodel辅助器",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/UmodelHelper.exe",
                FileName = "UmodelHelper.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "cmake-gui",
                DisplayName = "cmakegui汉化版",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/cmake-gui.exe",
                FileName = "cmake-gui.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
            {
                Name = "QuickWaveBank",
                DisplayName = "xwb打包解包工具",
                DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/QuickWaveBank.exe",
                FileName = "QuickWaveBank.exe",
                IsExternalTool = true,
                IsBuiltInDll = false
            },
            new PluginInfo
                {
                    Name = "CpkFileBuilder",
                    DisplayName = "CPK官方打包解包工具",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CpkFileBuilder.zip",
                    FileName = "CpkFileBuilder.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "CpkFileBuilder.exe",
                    ExtractFolder = "CpkFileBuilder"
                },
                new PluginInfo
                {
                    Name = "IDM",
                    DisplayName = "IDM下载器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/IDM.zip",
                    FileName = "IDM.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "IDMan.exe",
                    ExtractFolder = "IDM"
                },
                new PluginInfo
                {
                    Name = "PVRViewer",
                    DisplayName = "世嘉游戏PVR查看器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/PVRViewer.zip",
                    FileName = "PVRViewer.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "PVRViewer.exe",
                    ExtractFolder = "PVRViewer"
                },
                new PluginInfo
                {
                    Name = "GD-ROM-Explorer",
                    DisplayName = "世嘉游戏rom解包器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/GD-ROM-Explorer.zip",
                    FileName = "GD-ROM-Explorer.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "GD-ROM Explorer.exe",
                    ExtractFolder = "GD-ROM-Explorer"
                },
                new PluginInfo
                {
                    Name = "CDmage",
                    DisplayName = "光盘rom解包器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CDmage.zip",
                    FileName = "CDmage.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "CDmage.exe",
                    ExtractFolder = "CDmage"
                },
                new PluginInfo
                {
                    Name = "VGMTrans",
                    DisplayName = "VGMTrans音频提取器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/VGMTrans.zip",
                    FileName = "VGMTrans.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "VGMTrans.exe",
                    ExtractFolder = "VGMTrans"
                },
                new PluginInfo
                {
                    Name = "CitricComposer",
                    DisplayName = "柠檬音乐工坊",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CitricComposer.zip",
                    FileName = "CitricComposer.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "Citric Composer.exe",
                    ExtractFolder = "CitricComposer"
                },
                new PluginInfo
                {
                    Name = "toolbox",
                    DisplayName = "任天堂toolbox",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/toolbox.zip",
                    FileName = "toolbox.zip",
                    IsExternalTool = true,
                    IsBuiltInDll = false,
                    IsZipFile = true,
                    ExeFileName = "toolbox.exe",
                    ExtractFolder = "toolbox"
                },
                new PluginInfo
                {
                    Name = "CPKBrowser.exe",
                    DisplayName = "CPK浏览器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/CPKBrowser.exe",
                    FileName = "CPKBrowser.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false
                },
                new PluginInfo
                {
                    Name = "Nartools.exe",
                    DisplayName = "CSOL-Nar解包器",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/Nartools.exe",
                    FileName = "Nartools.exe",
                    IsExternalTool = true,
                    IsBuiltInDll = false
                },
                new PluginInfo
                {
                    Name = "FSBank",
                    DisplayName = "FSB打包工具",
                    DownloadUrl = "https://gitee.com/valkylia-goddess/AssetStudio-Neptune/releases/download/down/fsbank.zip",
                    FileName = "fsbank.zip",
                   IsExternalTool = true,
                   IsBuiltInDll = false,
                   IsZipFile = true,
                   ExeFileName = "fsbank.exe",
                   ExtractFolder = "fsbank"
                }
        };

        public static string pluginsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins");

        public static void InitializePlugins()
        {
            if (!Directory.Exists(pluginsDirectory))
            {
                Directory.CreateDirectory(pluginsDirectory);
            }

            foreach (var plugin in plugins)
            {
                string filePath = FindExecutableFile(plugin);
                plugin.IsDownloaded = filePath != null && File.Exists(filePath);

                Debug.WriteLine($"{plugin.DisplayName}: IsDownloaded = {plugin.IsDownloaded}, Path = {filePath}");
            }
        }
        private static string FindExecutableFile(PluginInfo plugin)
        {
            if (plugin.IsZipFile && !string.IsNullOrEmpty(plugin.ExtractFolder))
            {
                string extractFolderPath = Path.Combine(pluginsDirectory, plugin.ExtractFolder);

                if (!Directory.Exists(extractFolderPath))
                    return null;

                string directPath = Path.Combine(extractFolderPath, plugin.ExeFileName);
                if (File.Exists(directPath))
                    return directPath;

                try
                {
                    var files = Directory.GetFiles(extractFolderPath, plugin.ExeFileName, SearchOption.AllDirectories);
                    if (files.Length > 0)
                        return files[0];

                    var allExeFiles = Directory.GetFiles(extractFolderPath, "*.exe", SearchOption.AllDirectories);
                    if (allExeFiles.Length > 0)
                    {
                        var bestMatch = allExeFiles.FirstOrDefault(f =>
                            Path.GetFileNameWithoutExtension(f).Contains(plugin.Name, StringComparison.OrdinalIgnoreCase) ||
                            Path.GetFileNameWithoutExtension(f).Contains(Path.GetFileNameWithoutExtension(plugin.ExeFileName), StringComparison.OrdinalIgnoreCase));

                        return bestMatch ?? allExeFiles[0];
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"查找可执行文件时出错:{ex.Message}");
                    return null;
                }
            }
            else if (plugin.IsBuiltInDll)
            {
                string filePath = Path.Combine(pluginsDirectory, plugin.FileName);
                return File.Exists(filePath) ? filePath : null;
            }
            else
            {
                string filePath = Path.Combine(pluginsDirectory, plugin.FileName);
                return File.Exists(filePath) ? filePath : null;
            }

            return null;
        }

        private static void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
        {
            if (!target.Exists)
            {
                target.Create();
            }

            foreach (FileInfo file in source.GetFiles())
            {
                file.CopyTo(Path.Combine(target.FullName, file.Name), true);
            }

            foreach (DirectoryInfo subDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(subDir.Name);
                CopyDirectory(subDir, nextTargetSubDir);
            }
        }
        public static ToolStripMenuItem CreatePluginMenuItem(PluginInfo plugin)
        {
            var menuItem = new ToolStripMenuItem();
            menuItem.Name = $"toolStripMenuItem_{plugin.Name}";
            menuItem.Size = new System.Drawing.Size(180, 22);

            UpdateMainMenuItemText(plugin, menuItem);

            var downloadItem = new ToolStripMenuItem("下载");
            downloadItem.Click += (sender, e) => DownloadPlugin(plugin, menuItem);

            var launchItem = new ToolStripMenuItem("启动");
            launchItem.Click += (sender, e) => LaunchPlugin(plugin);

            var uninstallItem = new ToolStripMenuItem("卸载");
            uninstallItem.Click += (sender, e) => UninstallPlugin(plugin, menuItem);

            menuItem.DropDownItems.Add(downloadItem);
            menuItem.DropDownItems.Add(launchItem);
            menuItem.DropDownItems.Add(uninstallItem);

            UpdateSubMenuItemsState(plugin, downloadItem, launchItem, uninstallItem);

            menuItem.MouseEnter += (sender, e) =>
            {
                string detectedPath = FindExecutableFile(plugin);
                bool fileExists = detectedPath != null && File.Exists(detectedPath);

                if (fileExists != plugin.IsDownloaded)
                {
                    plugin.IsDownloaded = fileExists;
                    UpdateMainMenuItemText(plugin, menuItem);
                    UpdateSubMenuItemsState(plugin, downloadItem, launchItem, uninstallItem);
                }

                CloseOtherPluginDropDowns(menuItem);
                menuItem.ShowDropDown();
            };

            menuItem.MouseLeave += (sender, e) =>
            {
                var clientRect = menuItem.Bounds;
                var screenRect = menuItem.GetCurrentParent().RectangleToScreen(clientRect);
                var mousePos = Control.MousePosition;

                bool isMouseInDropDown = menuItem.DropDown.Visible &&
                                        menuItem.DropDown.Bounds.Contains(Control.MousePosition);

                if (!screenRect.Contains(mousePos) && !isMouseInDropDown)
                {
                    menuItem.HideDropDown();
                }
            };

            menuItem.DropDown.MouseLeave += (sender, e) =>
            {
                var mousePos = Control.MousePosition;
                var menuItemScreenRect = menuItem.GetCurrentParent().RectangleToScreen(menuItem.Bounds);

                if (!menuItemScreenRect.Contains(mousePos) &&
                    !menuItem.DropDown.Bounds.Contains(menuItem.DropDown.PointToClient(mousePos)))
                {
                    menuItem.HideDropDown();
                }
            };

            menuItem.Click += (sender, e) =>
            {

                if (plugin.IsDownloaded)
                {
                    LaunchPlugin(plugin);
                }
                else
                {
                    DownloadPlugin(plugin, menuItem);
                }
            };
            return menuItem;
        }

        private static void CloseOtherPluginDropDowns(ToolStripMenuItem currentMenuItem)
        {
            var parentMenu = currentMenuItem.Owner as MenuStrip;
            if (parentMenu != null)
            {
                foreach (ToolStripItem item in parentMenu.Items)
                {
                    var pluginMenu = item as ToolStripMenuItem;
                    if (pluginMenu != null && pluginMenu.Text == "插件")
                    {
                        foreach (ToolStripItem pluginItem in pluginMenu.DropDownItems)
                        {
                            var pluginMenuItem = pluginItem as ToolStripMenuItem;
                            if (pluginMenuItem != null && pluginMenuItem != currentMenuItem && pluginMenuItem.DropDown.Visible)
                            {
                                pluginMenuItem.HideDropDown();
                            }
                        }
                        break;
                    }
                }
            }
        }

        private static void UpdateMainMenuItemText(PluginInfo plugin, ToolStripMenuItem menuItem)
        {
            if (plugin.IsDownloaded)
            {
                menuItem.Text = $"{plugin.DisplayName} ✓";
            }
            else
            {
                menuItem.Text = plugin.DisplayName;
            }
        }

        private static void UpdateSubMenuItemsState(PluginInfo plugin, ToolStripMenuItem downloadItem,
    ToolStripMenuItem launchItem, ToolStripMenuItem uninstallItem)
        {
            downloadItem.Enabled = !plugin.IsDownloaded;
            launchItem.Enabled = plugin.IsDownloaded;
            uninstallItem.Enabled = plugin.IsDownloaded;
            if (plugin.IsDownloaded)
            {
                downloadItem.Text = "下载 ✓";
            }
            else
            {
                downloadItem.Text = "下载";
            }
        }
        public class DownloadSpeedCalculator
        {
            private DateTime startTime;
            private long totalBytes;
            private DateTime lastUpdateTime;
            private long lastBytes;
            private double smoothedSpeed = 0;

            public void Start()
            {
                startTime = DateTime.Now;
                lastUpdateTime = startTime;
                totalBytes = 0;
                lastBytes = 0;
                smoothedSpeed = 0;
            }

            public void AddBytes(long bytes)
            {
                totalBytes += bytes;
            }

            public void Stop()
            {
            }

            public double ElapsedTime => (DateTime.Now - startTime).TotalSeconds;

            public (double Speed, string Unit, string ETA) GetSpeedInfo(long downloadedBytes, long totalBytes)
            {
                var currentTime = DateTime.Now;
                var timeDiff = (currentTime - lastUpdateTime).TotalSeconds;

                if (timeDiff < 0.1)
                {
                    return (smoothedSpeed, smoothedSpeed > 1024 ? "MB/s" : "KB/s", "");
                }

                double currentSpeed = (downloadedBytes - lastBytes) / timeDiff / 1024;

                if (smoothedSpeed == 0)
                {
                    smoothedSpeed = currentSpeed;
                }
                else
                {
                    smoothedSpeed = 0.7 * smoothedSpeed + 0.3 * currentSpeed;
                }

                lastUpdateTime = currentTime;
                lastBytes = downloadedBytes;

                double speed;
                string unit;

                if (smoothedSpeed > 1024)
                {
                    speed = smoothedSpeed / 1024;
                    unit = "MB/s";
                }
                else
                {
                    speed = smoothedSpeed;
                    unit = "KB/s";
                }

                string eta = "";
                if (totalBytes > 0)
                {
                    long remainingBytes = totalBytes - downloadedBytes;
                    if (remainingBytes > 0 && smoothedSpeed > 0)
                    {
                        double etaSeconds = remainingBytes / (smoothedSpeed * 1024);
                        if (etaSeconds < 60)
                        {
                            eta = $"{etaSeconds:F0}秒";
                        }
                        else if (etaSeconds < 3600)
                        {
                            eta = $"{etaSeconds / 60:F0}分";
                        }
                        else
                        {
                            eta = $"{etaSeconds / 3600:F1}小时";
                        }
                    }
                    else
                    {
                        eta = "完成";
                    }
                }

                return (speed, unit, eta);
            }
        }
        private static void DownloadPlugin(PluginInfo plugin, ToolStripMenuItem menuItem)
        {
            if (plugin.IsDownloaded)
            {
                LaunchPlugin(plugin);
                return;
            }

            var downloadDialog = new DownloadProgressForm(plugin);
            downloadDialog.FormClosed += (s, e) =>
            {
                if (downloadDialog.DialogResult == DialogResult.OK)
                {
                    string filePath = Path.Combine(pluginsDirectory, plugin.FileName);

                    if (plugin.IsZipFile && File.Exists(filePath))
                    {
                        try
                        {
                            string extractPath = Path.Combine(pluginsDirectory, plugin.ExtractFolder);

                            if (Directory.Exists(extractPath))
                            {
                                Directory.Delete(extractPath, true);
                            }

                            Directory.CreateDirectory(extractPath);

                            System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath, true);

                            string foundExePath = FindExecutableFile(plugin);
                            if (foundExePath == null)
                            {
                                throw new FileNotFoundException($"在解压后的文件中找不到 {plugin.ExeFileName}");
                            }

                            File.Delete(filePath);

                            Debug.WriteLine($"{plugin.DisplayName} 解压完成，找到文件:{foundExePath}");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"解压失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }

                    InitializePlugins();

                    UpdateMainMenuItemText(plugin, menuItem);
                    if (menuItem.DropDownItems.Count >= 3)
                    {
                        UpdateSubMenuItemsState(plugin,
                            menuItem.DropDownItems[0] as ToolStripMenuItem,
                            menuItem.DropDownItems[1] as ToolStripMenuItem,
                            menuItem.DropDownItems[2] as ToolStripMenuItem);
                    }

                    MessageBox.Show($"{plugin.DisplayName}下载完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    InitializePlugins();
                }
                downloadDialog.Dispose();
            };

            downloadDialog.Show();
        }

        public static void LaunchPlugin(PluginInfo plugin)
        {
            if (!plugin.IsDownloaded)
            {
                MessageBox.Show($"请先下载{plugin.DisplayName}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                string filePath = FindExecutableFile(plugin);

                if (filePath == null)
                {
                    plugin.IsDownloaded = false;
                    MessageBox.Show($"{plugin.DisplayName} 文件不存在，请重新下载", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (plugin.IsExternalTool || plugin.IsZipFile)
                {
                    string workingDirectory = Path.GetDirectoryName(filePath);
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = filePath,
                        WorkingDirectory = workingDirectory,
                        UseShellExecute = true
                    };
                    Process.Start(startInfo);
                }
                else if (plugin.IsBuiltInDll)
                {
                    LaunchBuiltInDll(plugin, filePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动{plugin.DisplayName}失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void LaunchBuiltInDll(PluginInfo plugin, string filePath)
        {
            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

                Assembly assembly = Assembly.LoadFrom(filePath);

                var winFormsTypes = assembly.GetTypes()
                    .Where(t => typeof(Form).IsAssignableFrom(t) && !t.IsAbstract)
                    .ToList();

                var wpfWindowTypes = new List<Type>();
                try
                {
                    Type wpfWindowType = Type.GetType("System.Windows.Window, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                    if (wpfWindowType != null)
                    {
                        wpfWindowTypes = assembly.GetTypes()
                            .Where(t => wpfWindowType.IsAssignableFrom(t) && !t.IsAbstract)
                            .ToList();
                    }
                }
                catch
                {
                }

                if (wpfWindowTypes.Count == 0 && winFormsTypes.Count == 0)
                {
                    throw new Exception($"在{plugin.FileName}中找不到窗体类(WPF Window或WinForms Form)");
                }

                Type mainWindowType = null;

                if (plugin.Name.Contains("SuperToolbox", StringComparison.OrdinalIgnoreCase) ||
                    plugin.DisplayName.Contains("超级工具箱", StringComparison.OrdinalIgnoreCase))
                {
                    mainWindowType = winFormsTypes.FirstOrDefault(t =>
                        t.Name.Contains("SuperToolbox", StringComparison.OrdinalIgnoreCase) ||
                        t.FullName.Contains("SuperToolbox", StringComparison.OrdinalIgnoreCase) ||
                        t.Name.Contains("MainForm", StringComparison.OrdinalIgnoreCase) ||
                        t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase));

                    if (mainWindowType == null && winFormsTypes.Count > 0)
                    {
                        mainWindowType = winFormsTypes[0];
                    }
                }

                if (mainWindowType == null)
                {
                    mainWindowType = winFormsTypes.FirstOrDefault(t =>
                        t.Name.Contains("MainForm", StringComparison.OrdinalIgnoreCase) ||
                        t.Name.Equals("MainForm", StringComparison.OrdinalIgnoreCase));
                }

                if (mainWindowType == null)
                {
                    mainWindowType = winFormsTypes.FirstOrDefault(t =>
                        t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase));
                }

                if (mainWindowType == null && wpfWindowTypes.Count > 0)
                {
                    mainWindowType = wpfWindowTypes.FirstOrDefault(t =>
                        t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase)) ?? wpfWindowTypes[0];
                }

                if (mainWindowType == null)
                {
                    if (winFormsTypes.Count > 0)
                        mainWindowType = winFormsTypes[0];
                    else if (wpfWindowTypes.Count > 0)
                        mainWindowType = wpfWindowTypes[0];
                }

                if (mainWindowType == null)
                {
                    throw new Exception("无法确定主窗口类型");
                }

                if (IsWpfWindowType(mainWindowType))
                {
                    LaunchWpfWindow(plugin, new List<Type> { mainWindowType });
                }
                else
                {
                    LaunchWinFormsForm(plugin, new List<Type> { mainWindowType });
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                var loaderExceptions = ex.LoaderExceptions;
                StringBuilder sb = new StringBuilder();

                bool isSuperToolbox = plugin.Name.Contains("SuperToolbox", StringComparison.OrdinalIgnoreCase) ||
                                     plugin.DisplayName.Contains("超级工具箱", StringComparison.OrdinalIgnoreCase);

                if (isSuperToolbox)
                {
                    sb.AppendLine($"超级工具箱加载时遇到依赖问题，尝试忽略依赖继续运行:");
                }
                else
                {
                    sb.AppendLine($"加载插件时遇到依赖问题，尝试继续运行:");
                }

                foreach (var loaderException in loaderExceptions)
                {
                    if (loaderException is FileNotFoundException fileNotFound)
                    {
                        if (isSuperToolbox && fileNotFound.FileName != null &&
                            fileNotFound.FileName.Contains("CriFsV2Lib.Definitions", StringComparison.OrdinalIgnoreCase))
                        {
                            continue; 
                        }
                        sb.AppendLine($"缺失依赖:{fileNotFound.FileName}");
                    }
                }

                var loadableTypes = ex.Types.Where(t => t != null);

                var winFormsTypes = loadableTypes
                    .Where(t => typeof(Form).IsAssignableFrom(t) && !t.IsAbstract)
                    .ToList();

                var wpfWindowTypes = new List<Type>();
                try
                {
                    Type wpfWindowType = Type.GetType("System.Windows.Window, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                    if (wpfWindowType != null)
                    {
                        wpfWindowTypes = loadableTypes
                            .Where(t => wpfWindowType.IsAssignableFrom(t) && !t.IsAbstract)
                            .ToList();
                    }
                }
                catch
                {
                }

                if (winFormsTypes.Count > 0 || wpfWindowTypes.Count > 0)
                {
                    try
                    {
                        Type mainWindowType = null;

                        if (isSuperToolbox)
                        {
                            mainWindowType = winFormsTypes.FirstOrDefault(t =>
                                t.Name.Contains("SuperToolbox", StringComparison.OrdinalIgnoreCase) ||
                                t.FullName.Contains("SuperToolbox", StringComparison.OrdinalIgnoreCase) ||
                                t.Name.Contains("MainForm", StringComparison.OrdinalIgnoreCase) ||
                                t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase));

                            if (mainWindowType == null && winFormsTypes.Count > 0)
                            {
                                mainWindowType = winFormsTypes[0];
                            }
                        }

                        if (mainWindowType == null)
                        {
                            mainWindowType = winFormsTypes.FirstOrDefault(t =>
                                t.Name.Contains("MainForm", StringComparison.OrdinalIgnoreCase) ||
                                t.Name.Equals("MainForm", StringComparison.OrdinalIgnoreCase));
                        }

                        if (mainWindowType == null)
                        {
                            mainWindowType = winFormsTypes.FirstOrDefault(t =>
                                t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase));
                        }

                        if (mainWindowType == null && wpfWindowTypes.Count > 0)
                        {
                            mainWindowType = wpfWindowTypes.FirstOrDefault(t =>
                                t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase)) ?? wpfWindowTypes[0];
                        }

                        if (mainWindowType == null)
                        {
                            if (winFormsTypes.Count > 0)
                                mainWindowType = winFormsTypes[0];
                            else if (wpfWindowTypes.Count > 0)
                                mainWindowType = wpfWindowTypes[0];
                        }

                        if (mainWindowType != null)
                        {
                            if (IsWpfWindowType(mainWindowType))
                            {
                                LaunchWpfWindow(plugin, new List<Type> { mainWindowType });
                            }
                            else
                            {
                                LaunchWinFormsForm(plugin, new List<Type> { mainWindowType });
                            }

                            if (!isSuperToolbox)
                            {
                                MessageBox.Show($"{sb.ToString()}\n\n插件可能部分功能受限。",
                                    "依赖警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            return;
                        }
                    }
                    catch (Exception createEx)
                    {
                        throw new Exception($"创建窗体实例失败:{createEx.Message}\n{sb}", createEx);
                    }
                }

                throw new Exception($"加载插件失败:\n{sb}", ex);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载内置DLL插件失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
            }
        }

        private static bool IsWpfWindowType(Type type)
        {
            try
            {
                Type wpfWindowType = Type.GetType("System.Windows.Window, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                return wpfWindowType != null && wpfWindowType.IsAssignableFrom(type);
            }
            catch
            {
                return false;
            }
        }
        private static void LaunchWpfWindow(PluginInfo plugin, List<Type> windowTypes)
        {
            try
            {
                Type mainWindowType = windowTypes.FirstOrDefault(t =>
                    t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase)) ?? windowTypes[0];

                if (mainWindowType == null)
                {
                    throw new Exception("无法确定主窗口类型");
                }

                EnsureWpfApplication();

                var mainWindow = Activator.CreateInstance(mainWindowType);
                if (mainWindow == null)
                {
                    throw new Exception($"无法创建WPF窗口实例:{mainWindowType.FullName}");
                }

                var windowStartupLocationProperty = mainWindowType.GetProperty("WindowStartupLocation");
                if (windowStartupLocationProperty != null)
                {
                    var centerScreenValue = Enum.Parse(windowStartupLocationProperty.PropertyType, "CenterScreen");
                    windowStartupLocationProperty.SetValue(mainWindow, centerScreenValue);
                }

                var showMethod = mainWindowType.GetMethod("Show", Type.EmptyTypes);
                if (showMethod != null)
                {
                    showMethod.Invoke(mainWindow, null);
                }
                else
                {
                    throw new Exception($"找不到Show方法:{mainWindowType.FullName}");
                }

                var activateMethod = mainWindowType.GetMethod("Activate", Type.EmptyTypes);
                activateMethod?.Invoke(mainWindow, null);
            }
            catch (Exception ex)
            {
                throw new Exception($"启动WPF窗口失败:{ex.Message}", ex);
            }
        }

        private static void EnsureWpfApplication()
        {
            try
            {
                var applicationType = Type.GetType("System.Windows.Application, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                if (applicationType == null)
                {
                    throw new Exception("未找到WPF PresentationFramework，无法启动WPF窗口");
                }

                var currentAppProperty = applicationType.GetProperty("Current");
                var currentApp = currentAppProperty?.GetValue(null);

                if (currentApp == null)
                {
                    var appConstructor = applicationType.GetConstructor(Type.EmptyTypes);
                    if (appConstructor != null)
                    {
                        currentApp = appConstructor.Invoke(null);

                        var shutdownModeProperty = applicationType.GetProperty("ShutdownMode");
                        if (shutdownModeProperty != null)
                        {
                            var onExplicitShutdownValue = Enum.Parse(shutdownModeProperty.PropertyType, "OnExplicitShutdown");
                            shutdownModeProperty.SetValue(currentApp, onExplicitShutdownValue);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"初始化WPF应用程序失败:{ex.Message}", ex);
            }
        }

        private static void LaunchWinFormsForm(PluginInfo plugin, List<Type> formTypes)
        {
            Type mainFormType = formTypes.FirstOrDefault(t =>
                t.Name.Contains("Main", StringComparison.OrdinalIgnoreCase)) ?? formTypes[0];

            Form existingInstance = Application.OpenForms.Cast<Form>()
                .FirstOrDefault(form => form.GetType() == mainFormType);

            if (existingInstance != null)
            {
                if (existingInstance.WindowState == FormWindowState.Minimized)
                {
                    existingInstance.WindowState = FormWindowState.Normal;
                }
                existingInstance.BringToFront();
                existingInstance.Focus();
                return;
            }

            Form mainForm = Activator.CreateInstance(mainFormType) as Form;
            if (mainForm != null)
            {
                mainForm.StartPosition = FormStartPosition.CenterScreen;
                mainForm.Show();
            }
            else
            {
                throw new Exception($"无法创建窗体实例:{mainFormType.FullName}");
            }
        }
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            try
            {
                string assemblyName = new AssemblyName(args.Name).Name;

                string pluginPath = Path.Combine(pluginsDirectory, assemblyName + ".dll");
                if (File.Exists(pluginPath))
                {
                    return Assembly.LoadFrom(pluginPath);
                }

                string currentPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName + ".dll");
                if (File.Exists(currentPath))
                {
                    return Assembly.LoadFrom(currentPath);
                }

                return null;
            }
            catch
            {
                return null;
            }
        }

        private static void UninstallPlugin(PluginInfo plugin, ToolStripMenuItem menuItem)
        {
            if (!plugin.IsDownloaded)
            {
                return;
            }

            var result = MessageBox.Show($"确定要卸载{plugin.DisplayName}吗？", "确认卸载",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    if (plugin.IsZipFile && !string.IsNullOrEmpty(plugin.ExtractFolder))
                    {
                        string extractFolderPath = Path.Combine(pluginsDirectory, plugin.ExtractFolder);
                        if (Directory.Exists(extractFolderPath))
                        {
                            Directory.Delete(extractFolderPath, true);
                        }
                    }
                    else
                    {
                        string filePath = Path.Combine(pluginsDirectory, plugin.FileName);
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }

                    InitializePlugins();

                    UpdateMainMenuItemText(plugin, menuItem);
                    if (menuItem.DropDownItems.Count >= 3)
                    {
                        UpdateSubMenuItemsState(plugin,
                            menuItem.DropDownItems[0] as ToolStripMenuItem,
                            menuItem.DropDownItems[1] as ToolStripMenuItem,
                            menuItem.DropDownItems[2] as ToolStripMenuItem);
                    }

                    MessageBox.Show($"{plugin.DisplayName}卸载完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"卸载{plugin.DisplayName}失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public static void AddMenuItemsToPluginMenu(ToolStripMenuItem pluginMenu)
        {
            InitializePlugins();

            pluginMenu.DropDownItems.Clear();

            foreach (var plugin in plugins)
            {
                var menuItem = CreatePluginMenuItem(plugin);
                pluginMenu.DropDownItems.Add(menuItem);
            }

            pluginMenu.DropDownItems.Add(new ToolStripSeparator());

            var managePluginsItem = new ToolStripMenuItem("插件管理器");
            managePluginsItem.Click += (sender, e) => ShowPluginManager();
            pluginMenu.DropDownItems.Add(managePluginsItem);
        }

        private static void ShowPluginManager()
        {
            var managerForm = new PluginManagerForm();
            managerForm.ShowDialog();
        }

        public static void AddMenuItemsToMainForm(MainForm mainForm)
        {
            var pluginToolStripMenuItem = mainForm.MenuStrip1.Items["toolStripMenuItem20"] as ToolStripMenuItem;
            if (pluginToolStripMenuItem != null)
            {
                AddMenuItemsToPluginMenu(pluginToolStripMenuItem);
            }
        }

        public class DownloadProgressForm : Form
        {
            private CancellationTokenSource cancellationTokenSource;
            private ProgressBar progressBar;
            private Label statusLabel;
            private Plugins.PluginInfo plugin;
            public bool IsDownloading { get; private set; }
            private bool isDownloadCompleted = false;
            private string filePath;
            private long totalBytes = 0;
            private readonly object lockObject = new object();
            private Label speedLabel;
            private Label etaLabel;
            private DownloadSpeedCalculator downloadSpeedCalculator;
            private long currentTotalBytes = 0;
            public DownloadProgressForm(Plugins.PluginInfo plugin)
            {
                this.plugin = plugin;
                this.cancellationTokenSource = new CancellationTokenSource();
                InitializeComponent();
                this.Load += async (s, e) => await StartDownloadAsync();
            }

            private void InitializeComponent()
            {
                this.Size = new Size(450, 200);
                this.Text = $"下载{plugin.DisplayName}";
                this.StartPosition = FormStartPosition.CenterScreen;
                this.FormBorderStyle = FormBorderStyle.FixedDialog;
                this.MaximizeBox = false;
                this.MinimizeBox = false;
                this.ShowInTaskbar = false;

                statusLabel = new Label
                {
                    Text = "准备下载...",
                    Location = new Point(20, 20),
                    Size = new Size(360, 20)
                };

                progressBar = new ProgressBar
                {
                    Location = new Point(20, 50),
                    Size = new Size(410, 23),
                    Style = ProgressBarStyle.Continuous
                };
                speedLabel = new Label
                {
                    Text = "速度: --",
                    Location = new Point(20, 80),
                    Size = new Size(200, 15)
                };
                etaLabel = new Label
                {
                    Text = "剩余时间: --",
                    Location = new Point(20, 100),
                    Size = new Size(200, 15)
                };
                var cancelButton = new Button
                {
                    Text = "取消",
                    Location = new Point(335, 130),
                    Size = new Size(95, 25)
                };
                cancelButton.Click += (s, e) =>
                {
                    cancellationTokenSource.Cancel();
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                };

                this.Controls.Add(statusLabel);
                this.Controls.Add(progressBar);
                this.Controls.Add(speedLabel);
                this.Controls.Add(etaLabel);
                this.Controls.Add(cancelButton);

                downloadSpeedCalculator = new DownloadSpeedCalculator();
            }

            private HttpClient CreateOptimizedHttpClient()
            {
                var handler = new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                    UseProxy = false,
                    UseCookies = false,
                    MaxConnectionsPerServer = 20
                };

                var client = new HttpClient(handler)
                {
                    Timeout = TimeSpan.FromMinutes(30)
                };

                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
                client.DefaultRequestHeaders.Add("Accept", "*/*");
                client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

                return client;
            }

            private async Task StartDownloadAsync()
            {
                IsDownloading = true;
                downloadSpeedCalculator.Start();
                try
                {
                    if (!Directory.Exists(Plugins.pluginsDirectory))
                    {
                        Directory.CreateDirectory(Plugins.pluginsDirectory);
                    }

                    filePath = Path.Combine(Plugins.pluginsDirectory, plugin.FileName);

                    totalBytes = await GetFileSize(plugin.DownloadUrl);

                    await DownloadFileWithProgressAsync(plugin.DownloadUrl, filePath);

                    statusLabel.Text = "下载完成！";
                    isDownloadCompleted = true;
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch (OperationCanceledException)
                {
                    DeleteIncompleteFile();
                    statusLabel.Text = "下载已取消";
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
                catch (Exception ex)
                {
                    DeleteIncompleteFile();
                    statusLabel.Text = $"下载错误:{ex.Message}";
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
                finally
                {
                    downloadSpeedCalculator.Stop();
                    IsDownloading = false;
                }
            }

            private async Task<long> GetFileSize(string url)
            {
                try
                {
                    using (var client = CreateOptimizedHttpClient())
                    using (var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url)))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            return response.Content.Headers.ContentLength ?? 0;
                        }
                    }
                }
                catch
                {
                }
                return 0;
            }

            private async Task DownloadFileWithProgressAsync(string fileUrl, string savePath)
            {
                using (var client = CreateOptimizedHttpClient())
                using (var response = await client.GetAsync(fileUrl, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();

                    if (totalBytes == 0)
                    {
                        totalBytes = response.Content.Headers.ContentLength ?? 0;
                    }
                    currentTotalBytes = totalBytes;
                    using (var contentStream = await response.Content.ReadAsStreamAsync())
                    using (var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                    {
                        var buffer = new byte[8192];
                        var currentBytesRead = 0L;
                        int bytesRead;

                        while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length, cancellationTokenSource.Token)) > 0)
                        {
                            await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationTokenSource.Token);
                            currentBytesRead += bytesRead;

                            if (totalBytes > 0)
                            {
                                var percentage = (int)((double)currentBytesRead / totalBytes * 100);
                                UpdateProgressUI(percentage, currentBytesRead);
                            }

                            cancellationTokenSource.Token.ThrowIfCancellationRequested();
                        }
                    }
                }
            }

            private string FormatFileSize(long bytes)
            {
                if (bytes >= 1024 * 1024 * 1024) // GB
                {
                    return $"{bytes / (1024.0 * 1024 * 1024):0.00} GB";
                }
                else if (bytes >= 1024 * 1024) // MB
                {
                    return $"{bytes / (1024.0 * 1024):0.00} MB";
                }
                else if (bytes >= 1024) // KB
                {
                    return $"{bytes / 1024.0:0.00} KB";
                }
                else // B
                {
                    return $"{bytes} B";
                }
            }
            private void UpdateProgressUI(int percentage, long bytesRead)
            {
                var speedInfo = downloadSpeedCalculator.GetSpeedInfo(bytesRead, totalBytes);

                if (progressBar.InvokeRequired)
                {
                    progressBar.Invoke(new Action(() => {
                        progressBar.Value = percentage;
                        statusLabel.Text = $"下载中: {percentage}% ({FormatFileSize(bytesRead)} / {FormatFileSize(totalBytes)})";
                        speedLabel.Text = $"速度: {speedInfo.Speed:F1} {speedInfo.Unit}";
                    }));
                }
                else
                {
                    progressBar.Value = percentage;
                    statusLabel.Text = $"下载中: {percentage}% ({FormatFileSize(bytesRead)} / {FormatFileSize(totalBytes)})";
                    speedLabel.Text = $"速度: {speedInfo.Speed:F1} {speedInfo.Unit}";
                }
            }

            private void DeleteIncompleteFile()
            {
                try
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
                catch
                {
                }
            }

            protected override void OnFormClosing(FormClosingEventArgs e)
            {
                if (IsDownloading && !isDownloadCompleted)
                {
                    var result = MessageBox.Show("下载正在进行中，确定要取消吗？",
                        "确认关闭", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (result == DialogResult.No)
                    {
                        e.Cancel = true;
                        return;
                    }
                    else
                    {
                        DeleteIncompleteFile();
                    }
                }

                cancellationTokenSource?.Cancel();
                base.OnFormClosing(e);
            }
        }

        public class PluginManagerForm : Form
        {
            private ListView listView;
            private Panel buttonPanel;

            public PluginManagerForm()
            {
                InitializeComponent();
                LoadPlugins();
            }

            private void InitializeComponent()
            {
                this.StartPosition = FormStartPosition.CenterScreen;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                this.MinimumSize = new Size(500, 300);
                this.Text = "插件管理器";
                this.Size = new Size(500, 400);

                var tableLayout = new TableLayoutPanel
                {
                    Dock = DockStyle.Fill,
                    RowCount = 2,
                    ColumnCount = 1
                };
                tableLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
                tableLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));

                listView = new ListView
                {
                    View = View.Details,
                    FullRowSelect = true,
                    GridLines = true,
                    Dock = DockStyle.Fill,
                    MultiSelect = false
                };

                listView.Columns.Add("插件名称", 100);
                listView.Columns.Add("状态", 100);
                listView.Columns.Add("文件", 100);
                listView.Columns.Add("类型", 100);

                buttonPanel = new Panel
                {
                    Dock = DockStyle.Fill,
                    Height = 50
                };

                var downloadButton = new Button { Text = "下载", Location = new Point(10, 10), Size = new Size(75, 23) };
                var launchButton = new Button { Text = "启动", Location = new Point(95, 10), Size = new Size(75, 23) };
                var uninstallButton = new Button { Text = "卸载", Location = new Point(180, 10), Size = new Size(75, 23) };
                var refreshButton = new Button { Text = "刷新", Location = new Point(265, 10), Size = new Size(75, 23) };
                var closeButton = new Button { Text = "关闭", Location = new Point(350, 10), Size = new Size(75, 23) };

                downloadButton.Click += (s, e) => DownloadSelected();
                launchButton.Click += (s, e) => LaunchSelected();
                uninstallButton.Click += (s, e) => UninstallSelected();
                refreshButton.Click += (s, e) => LoadPlugins();
                closeButton.Click += (s, e) => this.Close();

                buttonPanel.Controls.Add(downloadButton);
                buttonPanel.Controls.Add(launchButton);
                buttonPanel.Controls.Add(uninstallButton);
                buttonPanel.Controls.Add(refreshButton);
                buttonPanel.Controls.Add(closeButton);

                tableLayout.Controls.Add(listView, 0, 0);
                tableLayout.Controls.Add(buttonPanel, 0, 1);

                this.Controls.Add(tableLayout);

                this.Resize += (s, e) => AutoResizeColumns();
            }

            private void AutoResizeColumns()
            {
                if (listView != null && listView.Columns.Count > 0 && listView.Width > 0)
                {
                    int totalWidth = listView.Width - 25;
                    int columnCount = listView.Columns.Count;

                    int columnWidth = totalWidth / columnCount;
                    foreach (ColumnHeader column in listView.Columns)
                    {
                        column.Width = columnWidth;
                    }
                }
            }

            private void LoadPlugins()
            {
                listView.Items.Clear();
                foreach (var plugin in Plugins.plugins)
                {
                    string filePath = Plugins.FindExecutableFile(plugin);
                    plugin.IsDownloaded = filePath != null && File.Exists(filePath);

                    var item = new ListViewItem(plugin.DisplayName);
                    item.SubItems.Add(plugin.IsDownloaded ? "已下载" : "未下载");
                    item.SubItems.Add(plugin.FileName);

                    string pluginType = plugin.PluginType;

                    item.SubItems.Add(pluginType);
                    item.Tag = plugin;

                    if (plugin.IsDownloaded)
                    {
                        item.BackColor = SystemColors.Info;
                        item.ForeColor = SystemColors.InfoText;
                        {
                            item.BackColor = SystemColors.Control;
                            item.ForeColor = SystemColors.GrayText;
                        }
                    }
                    else
                    {
                        item.BackColor = SystemColors.ControlLight;
                        item.ForeColor = SystemColors.ControlText;
                    }

                    listView.Items.Add(item);
                }
            }

            private void DownloadSelected()
            {
                if (listView.SelectedItems.Count > 0)
                {
                    var plugin = listView.SelectedItems[0].Tag as Plugins.PluginInfo;
                    if (plugin != null)
                    {
                        var downloadDialog = new DownloadProgressForm(plugin);
                        downloadDialog.FormClosed += (s, e) =>
                        {
                            if (downloadDialog.DialogResult == DialogResult.OK)
                            {
                                Plugins.InitializePlugins();
                                LoadPlugins();

                                RefreshMainPluginMenu();

                                MessageBox.Show($"{plugin.DisplayName}下载完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            downloadDialog.Dispose();
                        };
                        downloadDialog.Show();
                    }
                }
            }
            private void LaunchSelected()
            {
                if (listView.SelectedItems.Count > 0)
                {
                    var plugin = listView.SelectedItems[0].Tag as Plugins.PluginInfo;
                    if (plugin != null && plugin.IsDownloaded)
                    {
                        Plugins.LaunchPlugin(plugin);
                    }
                }
            }
            private void UninstallSelected()
            {
                if (listView.SelectedItems.Count > 0)
                {
                    var plugin = listView.SelectedItems[0].Tag as Plugins.PluginInfo;
                    if (plugin != null && plugin.IsDownloaded)
                    {
                        var result = MessageBox.Show($"确定要卸载{plugin.DisplayName}吗？", "确认卸载",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                        if (result == DialogResult.Yes)
                        {
                            try
                            {
                                if (plugin.IsZipFile && !string.IsNullOrEmpty(plugin.ExtractFolder))
                                {
                                    string extractFolderPath = Path.Combine(Plugins.pluginsDirectory, plugin.ExtractFolder);
                                    if (Directory.Exists(extractFolderPath))
                                    {
                                        Directory.Delete(extractFolderPath, true);
                                    }
                                }
                                else
                                {
                                    string filePath = Path.Combine(Plugins.pluginsDirectory, plugin.FileName);
                                    if (File.Exists(filePath))
                                    {
                                        File.Delete(filePath);
                                    }
                                }

                                Plugins.InitializePlugins();
                                LoadPlugins();

                                RefreshMainPluginMenu();

                                MessageBox.Show($"{plugin.DisplayName}卸载完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"卸载{plugin.DisplayName}失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }

            private void RefreshMainPluginMenu()
            {
                try
                {
                    var mainForm = Application.OpenForms.OfType<MainForm>().FirstOrDefault();
                    if (mainForm != null)
                    {
                        var pluginMenu = mainForm.MenuStrip1.Items["toolStripMenuItem20"] as ToolStripMenuItem;
                        if (pluginMenu != null)
                        {
                            var ownerControl = pluginMenu.Owner;
                            if (ownerControl != null && ownerControl.InvokeRequired)
                            {
                                ownerControl.Invoke(new Action(() => Plugins.AddMenuItemsToPluginMenu(pluginMenu)));
                            }
                            else
                            {
                                Plugins.AddMenuItemsToPluginMenu(pluginMenu);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"刷新主菜单失败: {ex.Message}");
                }
            }
        }
    }
}